#include<stdio.h>
#include<iostream>
#include"mpi.h"
#include<math.h>
using namespace std;
int main(int argc, char *argv[])
{
  int rank, size;
  MPI_Status status;
  MPI_Init( &argc, &argv );
  MPI_Comm_size( MPI_COMM_WORLD, &size );
  MPI_Comm_rank( MPI_COMM_WORLD, &rank );
  if(size != 2)
  {
    cout<<"Its a pingpong program. Exact 2 players"<<endl;
    exit(1);
  }
  for( int i= (int)pow( 2, 10 ); i<= pow( 2, 20 ); i*=2 )
  {
    int *sdata = (int*)malloc(i*sizeof(int));
    int *rdata = (int*)malloc(i*sizeof(int));

    for( int j=0; j<i; j++ )
      sdata[j] = j;
    
    MPI_Barrier(MPI_COMM_WORLD);
    if(rank == 0)
    {
      double stime = MPI_Wtime();
      MPI_Send(sdata, i, MPI_INT, 1, 0, MPI_COMM_WORLD);
      MPI_Recv(rdata, i, MPI_INT, 1, 0, MPI_COMM_WORLD, &status);
      double ftime = MPI_Wtime();
      printf("Elapsed time for %d elements of integer is %e\n", i, (ftime-stime));
    }
    else
    {
      MPI_Recv(rdata, i, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
      MPI_Send(rdata, i, MPI_INT, 0, 0, MPI_COMM_WORLD);
    }
    free(sdata);
    free(rdata);
  }
  MPI_Finalize();
  return 0;
}
